<template>
  <div>
    <div>正投影相机</div>
    <div ref="webgl"></div>
  </div>
</template>
<script lang="ts" setup>
  import * as THREE from 'three';
  import { OrbitControls } from 'three/addons';
  import { onMounted, ref } from 'vue';

  const webgl: any = ref(null);
  let scene: any = null;
  let camera: any = null;
  let render: any = null;
  onMounted(() => {
    init();
  });
  function init() {
    scene = new THREE.Scene();

    // 正投影相机
    const width = window.innerWidth; //canvas画布宽度
    const height = window.innerHeight; //canvas画布高度
    const k = width / height; //canvas画布宽高比
    const s = 600; //控制left, right, top, bottom范围大小
    camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1, 8000);
    camera.position.set(300, 300, 300);
    camera.lookAt(scene.position);
    render = new THREE.WebGLRenderer();
    // 背景颜色
    render.setClearColor('#f1f2f6');
    render.setSize(width, height);
    webgl.value.appendChild(render.domElement);
    new OrbitControls(camera, render.domElement);
    const amLight = new THREE.AmbientLight(0xffffff);
    scene.add(amLight);
    const helper = new THREE.AxesHelper(200);
    scene.add(helper);

    const pointLight = new THREE.PointLight(0xffffff);

    pointLight.position.set(100, 100, 100);
    scene.add(pointLight);
    const pointLightHelper = new THREE.PointLightHelper(pointLight);
    scene.add(pointLightHelper);
    const material = new THREE.MeshBasicMaterial({
      color: '#2b88d8',
      // vertexColors: true, //默认false，设置为true表示使用顶点颜色渲染
      // transparent: true, //开启透明
      // opacity: 0.7, //设置透明度
      side: THREE.DoubleSide,
    });

    const materialMesh = new THREE.Mesh(new THREE.BoxGeometry(50, 50, 200), material);
    scene.add(materialMesh);
    renderFun();
  }
  function renderFun() {
    render.render(scene, camera);
    requestAnimationFrame(renderFun);
  }
  // onresize 事件会在窗口被调整大小时发生
  window.onresize = function () {
    const width = window.innerWidth; //canvas画布宽度
    const height = window.innerHeight; //canvas画布高度
    // 重置渲染器输出画布canvas尺寸
    render.setSize(width, height);
    // 2.1.更新相机参数
    const k = width / height; //canvas画布宽高比
    const s = 600; //控制left, right, top, bottom范围大小

    camera.left = -s * k;
    camera.right = s * k;
    // 2.2.相机的left, right, top, bottom属性变化了，通知threejs系统
    camera.updateProjectionMatrix();
  };
</script>
<style lang=""></style>
